package paf.ui;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;

import paf.model.DiagramExpressionModel;
import paf.model.Observable;
import paf.model.Class;
import paf.model.UseCase;
import paf.model.Connection;

public class ManageModelUI extends JPanel implements Observer, ActionListener {

	private DiagramExpressionModel model;
	private JPanel pnlClasses, pnlUseCases, pnlConnections;
	private JLabel lblClasses, lblUseCases, lblConnections;
	private JComboBox cmbClasses, cmbUseCases, cmbConnections;
	private JButton btnClasses, btnUseCases, btnConnections;
	
	protected ManageModelUI() {
		super();
		this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		this.setAlignmentX(LEFT_ALIGNMENT);
		
		this.model = DiagramExpressionModel.get();
		model.addObserver(this);
		
		pnlClasses = new JPanel(new FlowLayout(FlowLayout.LEADING));
		lblClasses = new JLabel("Delete Class");
		cmbClasses = new JComboBox();
		btnClasses = new JButton("Delete");
		btnClasses.addActionListener(this);
		
		pnlUseCases = new JPanel(new FlowLayout(FlowLayout.LEADING));
		lblUseCases = new JLabel("Delete Usecase");
		cmbUseCases= new JComboBox();
		btnUseCases = new JButton("Delete");
		btnUseCases.addActionListener(this);
		
		pnlConnections = new JPanel(new FlowLayout(FlowLayout.LEADING));
		lblConnections = new JLabel("Delete Connection");
		cmbConnections = new JComboBox();
		btnConnections = new JButton("Delete");
		btnConnections.addActionListener(this);
		
		update(model);
		renderView();
	}
	
	private void renderView() {
		this.add(lblClasses);
		pnlClasses.add(cmbClasses);
		pnlClasses.add(btnClasses);
		this.add(pnlClasses);
		
		this.add(lblUseCases);
		pnlUseCases.add(cmbUseCases);
		pnlUseCases.add(btnUseCases);
		this.add(pnlUseCases);
		
		this.add(lblConnections);
		pnlConnections.add(cmbConnections);
		pnlConnections.add(btnConnections);
		this.add(pnlConnections);
	}

	@Override
	public void update(Observable o) {
		cmbClasses.removeAllItems();
		for(Class c : model.getClasses()) {
			cmbClasses.addItem(c);
		}
		cmbUseCases.removeAllItems();
		for(UseCase u : model.getUseCases()) {
			cmbUseCases.addItem(u);
		}
		cmbConnections.removeAllItems();
		for(Connection c : model.getConnections()) {
			cmbConnections.addItem(c);
		}
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == btnClasses) {
			model.removeConnectionClass((Class) cmbClasses.getSelectedItem());
		} else if(e.getSource() == btnUseCases) {
			model.removeConnectionUseCase((UseCase) cmbUseCases.getSelectedItem());
		} else if(e.getSource() == btnConnections) {
			model.removeConnection((Connection) cmbConnections.getSelectedItem());
		}
	}

}
